package com.fcat.springboot.mybatis.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.fcat.springboot.mybatis.constant.CommonConstant;
import com.fcat.springboot.mybatis.service.TsuantoneBaseService;
import com.fcat.springboot.mybatis.util.JsonUtil;
import com.fcat.springboot.mybatis.vo.Model;
import com.fcat.springboot.mybatis.vo.Pair;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * @BelongsProject: fcat-base
 * @BelongsPackage: com.fcat.springboot.mybatis.controller
 * @Author: susen
 * @CreateTime: 2019-09-16 17:22
 * @Description:
 */
public class TsuantoneBaseController<Bsi extends TsuantoneBaseService,Entity,T> {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected Bsi bsi;



    @ApiOperation("add")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject add(@RequestBody Entity entity){
        int result=bsi.insertSelective(entity);
        if(result==0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }

    @ApiOperation("getById")
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject get(@PathVariable T id){
        return JsonUtil.getSuccessJsonObject(bsi.selectById(id));
    }

    @ApiOperation("updateById")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject update(@RequestBody Entity entity){
        int result=bsi.updateById(entity);
        if(result==0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }


    @ApiOperation("updateSelectiveById")
    @RequestMapping(value = "/updateSelectiveById",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updateSelectiveById(@RequestBody Entity entity){
        int result=bsi.updateSelectiveById(entity);
        if(result==0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }

    @ApiOperation("batchUpdateById")
    @RequestMapping(value = "/batchUpdateById",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject batchUpdateById(@RequestBody List<Entity> list){
        int result=bsi.batchUpdateById(list);
        if(result==0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }

    @ApiOperation("removeById")
    @RequestMapping(value = "/{id}",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject remove(@PathVariable T id){
        int result=bsi.deleteById(id);
        if(result <= 0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }

    @ApiOperation("getList")
    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject list(){
        return JsonUtil.getSuccessJsonObject(bsi.selectListAll());
    }


    @ApiOperation("listByPage")
    @RequestMapping(value = "/listByPage",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject listByPage(Integer pageNum, Integer pageSize){

        pageNum = pageNum == null? CommonConstant.PAGE_NUM:pageNum;
        pageSize = pageSize == null? CommonConstant.PAGE_SIZE:pageSize;

        PageHelper.startPage(pageNum, pageSize);
        List<Entity> tMenuList = bsi.selectListAll();
        PageInfo page = new PageInfo(tMenuList);
        return JsonUtil.getSuccessJsonObject(page);
    }



    @ApiOperation("getListByParams")
    @PostMapping("/getListByParams")
    @ResponseBody
//    public <Entity> JSONObject getListByParams(Integer pageNum, Integer pageSize,String orderParam,List<Pair> paramPair,Class<Entity> clazz){
    public   JSONObject getListByParams(@RequestBody Model<Entity> model){

        if(model.getPageNo()!=null){
            PageHelper.startPage(model.getPageNo(), model.getPageSize());
        }
        Example example=new Example(model.getT().getClass());

        Example.Criteria criteria=example.createCriteria();
        List<Pair> andParamPair=model.getAndParamPair();
        if(andParamPair!=null &&andParamPair.size()!=0){
            for (Pair pair : andParamPair) {
                criteria.andEqualTo(pair.getKey(),pair.getValue());
            }
        }
        List<Pair> likeParamPair=model.getLikeParamPair();
        if(likeParamPair!=null && likeParamPair.size()!=0){
            for (Pair pair : likeParamPair) {
                criteria.andLike(pair.getKey(),pair.getValue());
            }
        }
        if(model.getOrderParam()!=null &&model.getOrderParam().length()!=0){
            example.setOrderByClause(model.getOrderParam()+" "+model.getOrderType());
        }
        List<Entity> tMenuList=bsi.selectByExample(example);
        if(model.getPageNo()!=null){
            return JsonUtil.getSuccessJsonObject(new PageInfo(tMenuList));
        }

        return JsonUtil.getSuccessJsonObject(tMenuList);
    }


    /**
     * 获取所有请求参数，封装为map对象
     * @return
     */
    public Map<String,Object> getParameterMap(){
        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,Object> parameterMap = new HashMap<String,Object>();
        while (enumeration.hasMoreElements()){
            String key = enumeration.nextElement();
            String value = request.getParameter(key);
            parameterMap.put(key,value);
        }
        return parameterMap;
    }


    @ApiOperation("batchInserts")
    @RequestMapping(value = "/batchInserts",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject batchInsert(@RequestBody List<Entity> list) {
        int result=bsi.batchInserts(list);
        if(result==0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }
    public static List<Long> strArrToLongList(String str) {
        try {
            String[] strArr = str.split(",");
            Long[] longArr = new Long[strArr.length];
            for(int i=0;i<strArr.length;i++){
                longArr[i]=Long.valueOf(strArr[i]);
            }
            return Arrays.asList(longArr);
        } catch (Exception e) {
            return null;
        }
    }

    @ApiOperation("batchDeleteById")
    @RequestMapping(value = "/batchDeleteById",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject batchDeleteById(String str) {
        if(str==null || str.trim().equals(""))return JsonUtil.getFailJsonObject();
        List list=strArrToLongList(str);
        if(list==null || list.size()==0) return JsonUtil.getFailJsonObject();
        int result=bsi.batchDeleteById(list);
        if(result==0){
            return JsonUtil.getFailJsonObject();
        }else{
            return JsonUtil.getSuccessJsonObject();
        }
    }



}